package com.fgs.common.textWatcher;

import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

import com.fgs.common.R;
import com.fgs.common.utils.CommonUtil;
import com.fgs.common.utils.ToastUtil;


/**
 * @author fgs
 * @date 2020/5/16
 * @description
 **/

public class DecimalTextWatcher implements TextWatcher {
    private EditText editText;
    //小数点后的位数
    private int digit = 2;
    private OnDecimalTextChangeListener onDecimalTextChangeListener;

    public DecimalTextWatcher(EditText editText) {
        this.editText = editText;
    }

    public DecimalTextWatcher(EditText editText, int digit) {
        this.editText = editText;
        this.digit = digit;
    }

    public DecimalTextWatcher(EditText editText, OnDecimalTextChangeListener onDecimalTextChangeListener) {
        this.editText = editText;
        this.onDecimalTextChangeListener = onDecimalTextChangeListener;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable edt) {
        String temp = edt.toString();
        //第一个字符不为小数点
        if (edt.length() == 1 && edt.toString().equals(".")) {
            editText.setText("");
            return;
        }
        if (onDecimalTextChangeListener != null) {
            onDecimalTextChangeListener.onDecimalTextChange(edt.toString());
        }
        int posDot = temp.indexOf(".");
        if (posDot <= 0) return;
        if (digit == 2) {
            if (temp.length() - posDot - 1 > 2) {
                edt.delete(posDot + 3, posDot + 4);
                ToastUtil.showShortToast(CommonUtil.getContext().getResources().getString(R.string.tip_input_two_decimal));
            }
        } else if (digit == 3) {
            if (temp.length() - posDot - 1 > 3) {
                edt.delete(posDot + 4, posDot + 5);
                ToastUtil.showShortToast(CommonUtil.getContext().getResources().getString(R.string.tip_input_three_decimal));
            }
        }

    }

    public interface OnDecimalTextChangeListener {
        void onDecimalTextChange(String string);
    }
}
